<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRentalStore, type RentalOrder } from '@/stores/rental'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const rentalStore = useRentalStore()
const authStore = useAuthStore()
const myRentals = ref<RentalOrder[]>([])
const detailDialogVisible = ref(false)
const selectedOrder = ref<RentalOrder | null>(null)

onMounted(async () => {
  try {
    myRentals.value = await rentalStore.getCurrentUserRentals()
  } catch (error: any) {
    if (error.response?.status === 401) {
      ElMessage.error('用户未登录，请重新登录')
    } else {
      ElMessage.error('加载租赁记录失败')
    }
  }
})

const getStatusColor = (status: string) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'ACTIVE': return 'primary'
    case 'COMPLETED': return 'success'
    case 'CANCELLED': return 'danger'
    case 'OVERDUE': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'PENDING': return '待处理'
    case 'ACTIVE': return '租赁中'
    case 'COMPLETED': return '已完成'
    case 'CANCELLED': return '已取消'
    case 'OVERDUE': return '逾期'
    default: return '未知'
  }
}

const returnEquipment = async (order: RentalOrder) => {
  try {
    await ElMessageBox.confirm('确认归还此设备？', '归还确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    await rentalStore.returnEquipment(order.id)
    ElMessage.success('设备归还成功')
    myRentals.value = await rentalStore.getCurrentUserRentals()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('归还设备失败')
    }
  }
}

const showOrderDetail = (order: RentalOrder) => {
  selectedOrder.value = order
  detailDialogVisible.value = true
}
</script>

<template>
  <div class="my-rentals">
    <h1>我的租赁</h1>
    
    <div class="rental-summary">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="summary-card">
            <div class="summary-item">
              <div class="summary-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">当前租赁</div>
                <div class="summary-value">{{ myRentals.filter(r => r.status === 'PENDING').length }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="summary-card">
            <div class="summary-item">
              <div class="summary-icon active">
                <el-icon><Check /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">已完成</div>
                <div class="summary-value">{{ myRentals.filter(r => r.status === 'COMPLETED').length }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="summary-card">
            <div class="summary-item">
              <div class="summary-icon completed">
                <el-icon><Check /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">已归还</div>
                <div class="summary-value">{{ myRentals.filter(r => r.status === 'ACTIVE').length }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="summary-card">
            <div class="summary-item">
              <div class="summary-icon income">
                <el-icon><Money /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">总消费</div>
                <div class="summary-value">¥{{ myRentals.reduce((sum, r) => sum + r.totalAmount, 0) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-card class="rental-list">
      <template #header>
        <h2>租赁记录</h2>
      </template>
      
      <el-table :data="myRentals" stripe>
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column label="设备" width="200">
          <template #default="{ row }">
            <div>设备ID: {{ row.equipmentId }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="rentalStartDate" label="开始日期" width="120" />
        <el-table-column prop="rentalEndDate" label="结束日期" width="120" />
        <el-table-column prop="dailyRentPrice" label="日租金" width="100">
          <template #default="{ row }">
            ¥{{ row.dailyRentPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="100">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 'ACTIVE'" 
              type="primary" 
              size="small"
              @click="returnEquipment(row)"
            >
              归还设备
            </el-button>
            <el-button size="small" @click="showOrderDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ selectedOrder.equipmentId }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ selectedOrder.rentalStartDate }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ selectedOrder.rentalEndDate }}</el-descriptions-item>
          <el-descriptions-item label="计划归还日期">{{ selectedOrder.plannedReturnDate }}</el-descriptions-item>
          <el-descriptions-item label="实际归还日期">{{ selectedOrder.actualReturnDate || '暂未归还' }}</el-descriptions-item>
          <el-descriptions-item label="日租金">¥{{ selectedOrder.dailyRentPrice }}</el-descriptions-item>
          <el-descriptions-item label="押金">¥{{ selectedOrder.depositAmount }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ selectedOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ selectedOrder.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">{{ selectedOrder.updatedAt }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ selectedOrder.notes || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="selectedOrder && selectedOrder.status === 'ACTIVE'" 
          type="primary"
          @click="returnEquipment(selectedOrder)"
        >
          归还设备
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.my-rentals {
  padding: 20px;
}

.my-rentals h1 {
  margin-bottom: 30px;
  color: #303133;
}

.rental-summary {
  margin-bottom: 30px;
}

.summary-card :deep(.el-card__body) {
  padding: 16px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.summary-icon .el-icon {
  font-size: 20px;
  color: white;
}

.pending {
  background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
}

.active {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
}

.completed {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
}

.income {
  background: linear-gradient(135deg, #f759ab 0%, #ff85c0 100%);
}

.summary-content {
  flex: 1;
}

.summary-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.summary-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.rental-list h2 {
  margin: 0;
  color: #303133;
}
</style>